package com.zwc.kotlin.coroutines.core

sealed class Disposablelist {
    object Nil : Disposablelist()
    class Cons(val head: Disposable, val tail: Disposablelist) : Disposablelist()
}

fun Disposablelist.remove(disposable: Disposable): Disposablelist {
    return when (this) {
        Disposablelist.Nil -> this
        is Disposablelist.Cons -> {
            if (head == disposable) {
                return tail
            } else {
                Disposablelist.Cons(head, tail.remove(disposable))
            }
        }
    }
}

tailrec fun Disposablelist.forEach(action: (Disposable) -> Unit): Unit =
    when (this) {
        is Disposablelist.Cons -> {
            action(this.head)
            this.tail.forEach(action)
        }
        Disposablelist.Nil -> Unit
    }

inline fun <reified T : Disposable> Disposablelist.loopOn(crossinline action: (T) -> Unit) = forEach {
    when (it) {
        is T -> {
            action(it)
        }
    }
}
